/*
 * Copyright 2009-2010 Nanjing RedOrange ltd (http://www.red-orange.cn)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package redora;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import redora.api.Persistable;
import redora.exceptions.QueryException;

import java.util.Date;

/**
 * Base class for all the generated J2SE pojo classes.
 */
public abstract class PersistableBase {

    /** How is this object retrieved. By default (if for example the object is new) it's scope is assumed as Form. */
    public redora.api.fetch.Scope fetchScope;

    public boolean isNew;

    public Long id;
    public Date creationDate;
    public Date updateDate;

    public Long getId() {
        return id;
    }
    public void setId(@NotNull Long id) {
        assert this.id == null : "It is not allowed to modify the id";
        this.id = id;
    }

    public Date getCreationDate() {
        assert fetchScope != redora.api.fetch.Scope.List
                : "This object is fetched as Scope.List. Fetch the object with Table or Form scope instead.";
        return this.creationDate;
    }

    @Nullable
    public Date getUpdateDate() {
        assert fetchScope != redora.api.fetch.Scope.List
                : "This object is fetched as Scope.List. Fetch the object with Table or Form scope instead.";
        return this.updateDate;
    }

    /**
     * True if this has changed since given date. Only checks the pojo creation/update date, not the related
     * children.
     *
     * @param since (Mandatory) from date to check the change.
     * @return True is this has changed.
     */
    public boolean wasDirty(@NotNull Date since) throws QueryException {
        return since.before(getCreationDate()) || (getUpdateDate() != null && since.before(getUpdateDate()));
    }
}
